class TicTacToeGame {
  constructor() {
    this.playerId = null;
    this.symbol = null;
    this.gameId = null;
    this.yourTurn = false;
    this.gameActive = false;
    
    // DOM elements
    this.statusElement = document.getElementById('status');
    this.gameElement = document.getElementById('game');
    this.symbolElement = document.getElementById('symbol');
    this.gameStatusElement = document.getElementById('game-status');
    this.boardElement = document.getElementById('board');
    this.rematchButton = document.getElementById('rematch');
    this.rematchRequestElement = document.getElementById('rematch-request');
    this.acceptRematchButton = document.getElementById('accept-rematch');
    this.declineRematchButton = document.getElementById('decline-rematch');
    
    // Bind event listeners
    this.bindEvents();
    
    // Connect to WebSocket server
    this.connect();
  }
  
  bindEvents() {
    // Cell click events
    document.querySelectorAll('.cell').forEach(cell => {
      cell.addEventListener('click', (e) => {
        if (!this.gameActive || !this.yourTurn) return;
        
        const index = parseInt(e.target.dataset.index);
        if (isNaN(index)) return;
        
        this.makeMove(index);
      });
    });
    
    // Rematch events
    this.rematchButton.addEventListener('click', () => {
      this.requestRematch();
    });
    
    this.acceptRematchButton.addEventListener('click', () => {
      this.acceptRematch();
    });
    
    this.declineRematchButton.addEventListener('click', () => {
      this.declineRematch();
    });
  }
  
  connect() {
    // Use the current domain for WebSocket connection to support external access
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host;
    this.ws = new WebSocket(`${protocol}//${host}`);
    
    this.ws.onopen = () => {
      console.log('Connected to server');
      this.updateStatus('正在寻找对手...');
      
      // Request to find a game after a short delay
      setTimeout(() => {
        this.ws.send(JSON.stringify({ type: 'findGame' }));
      }, 1000);
    };
    
    this.ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        this.handleMessage(data);
      } catch (error) {
        console.error('Error parsing message:', error);
      }
    };
    
    this.ws.onclose = () => {
      console.log('Disconnected from server');
      this.updateStatus('与服务器断开连接');
    };
    
    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
      this.updateStatus('连接错误');
    };
  }
  
  handleMessage(data) {
    switch (data.type) {
      case 'playerId':
        this.playerId = data.playerId;
        console.log('Player ID:', this.playerId);
        break;
        
      case 'waitingForOpponent':
        this.updateStatus('正在等待对手加入...');
        break;
        
      case 'gameStart':
        this.symbol = data.symbol;
        this.yourTurn = data.yourTurn;
        this.gameActive = true;
        
        this.symbolElement.textContent = this.symbol;
        this.updateGameStatus();
        this.updateStatus('游戏开始');
        this.gameElement.classList.remove('hidden');
        
        // Reset board
        this.resetBoard();
        break;
        
      case 'moveMade':
        this.updateBoard(data.board);
        
        if (data.result) {
          this.handleGameResult(data.result);
        } else {
          this.yourTurn = data.yourTurn;
          this.updateGameStatus();
        }
        break;
        
      case 'opponentDisconnected':
        this.gameActive = false;
        this.updateStatus('对手已断开连接');
        this.gameStatusElement.textContent = '对手已断开连接';
        this.rematchButton.classList.add('hidden');
        break;
        
      case 'rematchRequested':
        this.rematchRequestElement.classList.remove('hidden');
        break;
        
      case 'rematchAccepted':
        this.gameActive = true;
        this.yourTurn = data.yourTurn;
        this.rematchRequestElement.classList.add('hidden');
        this.rematchButton.classList.remove('hidden');
        this.rematchButton.disabled = false;
        this.rematchButton.textContent = '再来一局';
        
        this.updateGameStatus();
        this.updateStatus('新游戏开始');
        
        // Reset board
        this.resetBoard();
        break;
        
      case 'error':
        console.error('Server error:', data.message);
        this.updateStatus(`错误: ${data.message}`);
        break;
        
      default:
        console.warn('Unknown message type:', data.type);
    }
  }
  
  makeMove(position) {
    if (!this.gameActive || !this.yourTurn) return;
    
    // Send move to server
    this.ws.send(JSON.stringify({
      type: 'makeMove',
      position
    }));
  }
  
  updateBoard(board) {
    const cells = document.querySelectorAll('.cell');
    cells.forEach((cell, index) => {
      cell.textContent = board[index] || '';
      cell.className = 'cell';
      if (board[index]) {
        cell.classList.add(board[index]);
      }
    });
  }
  
  resetBoard() {
    const cells = document.querySelectorAll('.cell');
    cells.forEach(cell => {
      cell.textContent = '';
      cell.className = 'cell';
    });
  }
  
  handleGameResult(result) {
    this.gameActive = false;
    
    if (result.winner) {
      this.gameStatusElement.textContent = result.winner === this.symbol ? 
        '你赢了!' : '你输了!';
    } else if (result.draw) {
      this.gameStatusElement.textContent = '平局!';
    }
    
    // Show rematch button
    this.rematchButton.classList.remove('hidden');
  }
  
  requestRematch() {
    this.ws.send(JSON.stringify({
      type: 'rematch'
    }));
    
    this.rematchButton.disabled = true;
    this.rematchButton.textContent = '等待对手接受...';
  }
  
  acceptRematch() {
    this.ws.send(JSON.stringify({
      type: 'rematch'
    }));
    
    this.rematchRequestElement.classList.add('hidden');
  }
  
  declineRematch() {
    this.rematchRequestElement.classList.add('hidden');
  }
  
  updateStatus(message) {
    this.statusElement.textContent = message;
  }
  
  updateGameStatus() {
    if (!this.gameActive) return;
    
    this.gameStatusElement.textContent = this.yourTurn ? 
      '轮到你了' : '等待对手';
  }
}

// Initialize the game when the page loads
document.addEventListener('DOMContentLoaded', () => {
  new TicTacToeGame();
});